package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.FriendNews;
import cn.wolfcode.trip.base.domain.FriendNewsByUserAndReplyData;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.FriendNewsCommentMapper;
import cn.wolfcode.trip.base.mapper.FriendNewsLikerMapper;
import cn.wolfcode.trip.base.mapper.FriendNewsMapper;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.query.FriendNewsQueryObject;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements IUserService{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FriendNewsMapper friendNewsMapper;
    @Autowired
    private FriendNewsLikerMapper friendNewsLikerMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private FriendNewsCommentMapper friendNewsCommentMapper;

    @Override
    public void userRegister(User user) {
       User temp = userMapper.selectUserByEmailAndPassword(user.getEmail(),null);
        //如果temp不为空 意味着邮箱存在 返回提示
        if(temp!=null){
            throw new RuntimeException("邮箱已经被注册了,请换一个");
        }

        //设置默认的背景
        user.setCoverImgUrl("/img/user/bg.jpeg");
        //设置默认的头像
        user.setHeadImgUrl("/img/user/head.jpg");
        //设置默认地址
        user.setPlace("广州");

        //注册成功 完成保存操作
        userMapper.insert(user);
    }


    @Override
    public User login(User user) {
        User temp = userMapper.selectUserByEmailAndPassword(user.getEmail(), user.getPassword());
        //如果User对象为空 表示用户不存在
        if (temp==null){
            throw new RuntimeException("账号或密码错误");
        }
        return temp;
    }


    @Override
    //远程校验邮箱
    public User checkEmail(String email) {
        return userMapper.checkEmail(email);
    }

    @Override
    public PageInfo getPageInfo(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<User> list = userMapper.selectForList(qo);
        return new PageInfo(list);
    }

    @Override
    public void userUpdate(User user) {
        userMapper.updateByPrimaryKey(user);
    }

    @Override
    public User get(Long userId) {
        return userMapper.selectByPrimaryKey(userId);
    }
    @Override
    public int getTravelNums(Long userId) {
        return userMapper.getTravelNums(userId);
    }

    @Override
    public List<Map> listAllFridends(Long id) {
        return userMapper.selectAllFridends(id);
    }

    @Override
    public User selectOneByNickName(String name) {
        return userMapper.selectOneByNickName(name);
    }


    @Override
    public List queryFriends(Long id) {
        List onePart=userMapper.queryByRoleOfInviter(id);
        List twoPart=userMapper.queryByRoleOfInvited(id);
        ArrayList<Map> friends = new ArrayList<>();
        friends.addAll(onePart);
        friends.addAll(twoPart);
        return friends;
    }

    @Override
    public List queryManyUsers(Long[] ids) {
        return userMapper.selectManyUsers(ids);
    }

    @Override
    public PageInfo queryFriendNews(Long id, FriendNewsQueryObject qo,Long currentUserId) {
        //自己的朋友圈
        List yourselfFriendNewsIds = friendNewsMapper.selectFriendNewsIds(currentUserId);
        List<Long> friendNewsIdsOfYourFriends=new ArrayList();;
        //当前用户朋友
        int friendIdsIndex=0;
        List<Map> friendsMap = queryFriends(currentUserId);
        Long[] friendIds=new Long[friendsMap.size()];
        for (Map friend : friendsMap) {
            friendIds[friendIdsIndex++]=(Long)friend.get("id");
        }
        if(friendIds.length>0) {
            List<User> friends = userMapper.selectManyUsers2(friendIds);
            friendNewsIdsOfYourFriends = new ArrayList();
            List<Long> pointedPersonIds = new ArrayList();
            List<Long> aitedPersonIds = new ArrayList();
            int index = 0;
            for (User friend : friends) {
                Set<FriendNews> friendNewsesOfYourFriend = friendNewsMapper.selectFriendNews(friend.getId());
                for (FriendNews friendNews : friendNewsesOfYourFriend) {
                    if (friendNews.getStatus() == 1) {   //指定某些朋友可见
                        pointedPersonIds = friendNewsMapper.selectPointedPersonIdsByFriendNewsId(friendNews.getId());
                        for (Long pointedPersonId : pointedPersonIds) {
                            if (pointedPersonId == currentUserId) {
                                friendNewsIdsOfYourFriends.add(friendNews.getId());
                            }
                        }
                    } else if (friendNews.getStatus() == 0) {//好友可见
                        friendNewsIdsOfYourFriends.add(friendNews.getId());
                    }
                    //@的朋友圈
                    aitedPersonIds = friendNewsMapper.selectAitedPersonIdsByFriendNewsId(friendNews.getId());
                    for (Long aitedPersonId : aitedPersonIds) {
                        if (aitedPersonId == currentUserId) {
                            friendNewsIdsOfYourFriends.add(friendNews.getId());
                        }
                    }
                }
            }
            //当前用户可看的朋友圈
            for (int i = 0; i < friendNewsIdsOfYourFriends.size(); i++) {
                yourselfFriendNewsIds.add(friendNewsIdsOfYourFriends.get(i));
            }
        }
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        //获取朋友圈的点赞记录
        List<FriendNews> dataList = addFriendNewsLikerForFriendNews(yourselfFriendNewsIds,friendNewsIdsOfYourFriends,currentUserId);

        //转换图片格式
        for (FriendNews friendNews : dataList) {
            ArrayList<Object> list = new ArrayList<>();
            if(friendNews.getPics()!=null){
                String[] pictures = friendNews.getPics().split(";");
                HashMap picMap;
                for (String picture : pictures) {
                    picMap= new HashMap();
                    picMap.put("picture",picture);
                    list.add(picMap);
                }
                friendNews.setPicsForHtml(list);
            }
        }
        return new PageInfo(dataList);
    }

    //获取朋友圈的点赞记录
    public List<FriendNews> addFriendNewsLikerForFriendNews(List<Long> yourselfFriendNewsIds,List<Long> friendNewsIdsOfYourFriends,Long currentUserId){

        Map<String, Object> appearForHtmlLikerMap = new HashMap<>();
        Set<FriendNews> friendNewsAfterAddLiker = new HashSet<>();
        FriendNews friendNews;
        //如果是自己动态
        yourselfFriendNewsIds.removeAll(friendNewsIdsOfYourFriends);
        for (Long yourselfFriendNewsId : yourselfFriendNewsIds) {
            friendNews = friendNewsMapper.selectByPrimaryKey(yourselfFriendNewsId);
            List maps1 = friendNewsLikerMapper.selectLikerByFriendNewsId(yourselfFriendNewsId);
            friendNews.setLiker(maps1);
            friendNewsAfterAddLiker.add(friendNews);
        }
        //如果是朋友动态
        for (Long friendNewsIdsOfYourFriend : friendNewsIdsOfYourFriends) {
            List appearForHtmlLiker=new ArrayList<>();
            List<Long> likersIds=friendNewsLikerMapper.selectLikerIdByFriendNewsId(friendNewsIdsOfYourFriend);
            friendNews = friendNewsMapper.selectByPrimaryKey(friendNewsIdsOfYourFriend);
            for (Long likersId : likersIds) {
                //如果是自己的点赞
                if(currentUserId==likersId){
                    appearForHtmlLikerMap=userMapper.selectAppearForHtmlLiker(currentUserId);
                    appearForHtmlLiker.add(appearForHtmlLikerMap);
                    friendNews.setLiker(appearForHtmlLiker);

                }
                //如果动态发表人的点赞
                Long friendNewsPublishPeopleId=friendNewsMapper.selectFriendNewsPublishPeopleIdByFriendNewsId(friendNewsIdsOfYourFriend);
                if(likersId==friendNewsPublishPeopleId){
                    appearForHtmlLikerMap=userMapper.selectAppearForHtmlLiker(friendNewsPublishPeopleId);
                    appearForHtmlLiker.add(appearForHtmlLikerMap);
                    friendNews.setLiker(appearForHtmlLiker);
                }
                //如果是动态发表人朋友的点赞也是自己的朋友的点赞
                List<Map> friends = userService.queryFriends(friendNewsPublishPeopleId);
                ArrayList<Long> friendNewsPublishPeopleFriends = new ArrayList<>();
                for (Map friend : friends) {
                    friendNewsPublishPeopleFriends.add((Long)friend.get("id"));
                }
                //
                List<Map> friends2 = userService.queryFriends(currentUserId);
                ArrayList<Long> yourFriends = new ArrayList<>();
                for (Map friend : friends2) {
                    yourFriends.add((Long)friend.get("id"));
                }
                //
                for (Long friendNewsPublishPeopleFriend : friendNewsPublishPeopleFriends) {
                    for (Long yourFriend : yourFriends) {
                        if(likersId==friendNewsPublishPeopleFriend && likersId==yourFriend){
                            appearForHtmlLikerMap=userMapper.selectAppearForHtmlLiker(likersId);
                            appearForHtmlLiker.add(appearForHtmlLikerMap);
                            friendNews.setLiker(appearForHtmlLiker);

                        }
                        //如果是动态发表人朋友的点赞,但不是自己的朋友的点赞
                    }
                }

            }
            friendNewsAfterAddLiker.add(friendNews);
        }
        ArrayList friendNewsesOfCombineYouAndYourFriends = new ArrayList<>(friendNewsAfterAddLiker);

        //封装动态的回复
        List<FriendNews> AddRepliesAddLikerFriendNewses = addFriendNewsRepliesForFriendNews(friendNewsesOfCombineYouAndYourFriends, currentUserId);
        return AddRepliesAddLikerFriendNewses;
    }

    public List<FriendNews> addFriendNewsRepliesForFriendNews(List<FriendNews> list,Long currentUserId){
        List appliesForFriendNewsList=new ArrayList();
        for (FriendNews friendNews : list) {
            List<Long> friendNewsCommentIds=new ArrayList<>();
            List<Long> onePartFriendNewsCommentIds=new ArrayList<>();
            Long friendNewsPublishPeopleId = friendNewsMapper.selectFriendNewsPublishPeopleIdByFriendNewsId(friendNews.getId());
            if (friendNewsPublishPeopleId==currentUserId){//如果是当前用户的动态
                onePartFriendNewsCommentIds=friendNewsCommentMapper.selectFriendNewsCommentIdsByFriendNewsId(friendNews.getId());
                friendNewsCommentIds.addAll(onePartFriendNewsCommentIds);
            }else {//如果是朋友的动态
                //根据动态id,查询出回复人和被回复人
                List<FriendNewsByUserAndReplyData> data=friendNewsCommentMapper.selectReplyAndByUserByFriendNewsId(friendNews.getId());
                //查询当前用户的朋友
                List<Map> friendsOfCurrentUser = userService.queryFriends(currentUserId);
                for (FriendNewsByUserAndReplyData datum : data) {
                    Long byUserId = datum.getByUserId();
                    Long replyId = datum.getReplyId();
                    //根据动态id,查询出回复人和被回复人,如果两者中其中一个含有当前用户,那此条回复可见
                    if(currentUserId==byUserId || currentUserId==replyId){
                        onePartFriendNewsCommentIds=friendNewsCommentMapper.selectFriendNewsCommentIdsByReplyAndByUser(replyId,byUserId,friendNews.getId());
                        friendNewsCommentIds.addAll(onePartFriendNewsCommentIds);
                    }else {
                        boolean temp1=false;
                        boolean temp2=false;
                        for (Map map : friendsOfCurrentUser) {
                            Long friendId= (Long) map.get("id");
                            //-1表示动态发表人
                            if(byUserId==-1){
                                if(friendNewsPublishPeopleId==friendId){
                                    temp1=true;
                                }
                            }
                            if(byUserId==friendId){
                                temp1=true;
                            }
                            if(replyId==friendId){
                                temp2=true;
                            }
                        }
                        //如果两者中都不含有当前用户,判断这两者都是当前用户的朋友,那此条回复可见
                        if(temp1 && temp2){
                            onePartFriendNewsCommentIds=friendNewsCommentMapper.selectFriendNewsCommentIdsByReplyAndByUser(replyId,byUserId,friendNews.getId());
                            friendNewsCommentIds.addAll(onePartFriendNewsCommentIds);
                        }
                    }

                }

            }
            //将回复绑定到动态中
            if (friendNewsCommentIds.size() > 0) {
                List allCommentsDataOfFriendNews = friendNewsCommentMapper.selectAllCommentsDataOfFriendNews(friendNewsCommentIds);
                Collections.sort(allCommentsDataOfFriendNews) ;
                friendNews.setReplies(allCommentsDataOfFriendNews);
            }
            appliesForFriendNewsList.add(friendNews);
        }
        Collections.sort(appliesForFriendNewsList) ;
        return appliesForFriendNewsList;

    }

}
